#include "Log.h"

Log::Log() {
}

Log::Log(string filename){
	this->filename = filename;
	this->is_debug = false;
	this->fl.l_type = F_WRLCK;
	this->fl.l_whence = SEEK_SET;
	this->fl.l_start = 0;
	this->fl.l_len = 0;
	this->fl.l_pid = getpid();
	this->fd = open ( filename.c_str(),O_CREAT|O_WRONLY,0777 );
}

Log::Log(Log &l){
	filename = l.filename;
	is_debug = l.is_debug;
	fl.l_type = F_WRLCK;
	fl.l_whence = SEEK_SET;
	fl.l_start = 0;
	fl.l_len = 0;
	fl.l_pid = getpid();
	fd = l.fd;
}

Log& Log::operator=(const Log &l) {
	filename = l.filename;
	is_debug = l.is_debug;
	fl.l_type = F_WRLCK;
	fl.l_whence = SEEK_SET;
	fl.l_start = 0;
	fl.l_len = 0;
	fl.l_pid = getpid();
	fd = l.fd;
	return *this;
 }

string Log::getDate(){
 	const int MAXLEN = 16;
	char s[MAXLEN];
	time_t t = time(0);
	strftime(s, MAXLEN, "%Y%m%d_%H%M%S", localtime(&t));
	return s;
}

void Log::activeDebug(bool active){
	is_debug = active;
}

void Log::debug(string logline){
	string tolog;
	tolog.append("[");
	tolog.append(getDate());
	tolog.append("]");
	tolog.append(logline);

	if ( is_debug ){
		cout << tolog << endl;
	}

	//tomar lock
	fl.l_type = F_WRLCK;
	fcntl (fd,F_SETLKW,&(fl));
	
	//escribir
	lseek (fd,0,SEEK_END);
	int resultado = write (fd,tolog.c_str(),strlen(tolog.c_str()));

	if ( resultado < 0 ){
		cerr << "Error al escribir en log " << endl;
	}

	//liberar lock
	fl.l_type = F_UNLCK;
	fcntl (fd,F_SETLK,&(fl));

}

Log::~Log(){
	close (fd);
}
